<?php

namespace App\Command\ResumeParsing\Service\ParsingSpecial;

use App\Command\ResumeParsing\Service\TranslateHelper;
use App\Service\FileHandler;
use EchoPHP\Facades\Log;

class ParsingLiepin2 extends ParsingSpecialXml {

    private $translateHelper;

    function __construct($helper) {
        parent::__construct($helper);
        $this->titleXpath = "//body/p[ppr/pbdr/bottom[@*[local-name()='w:color' and .='E7E7E7']]]";
        $this->translateHelper = new TranslateHelper();

        $this->get['template'] = function () {
            $this->listXPath("//templateTag[normalize-space()='templateTagName']");    //[contains(., 'templateTagName')][starts-with(normalize-space(), 'templateTagName')]
            $result = $this->xPath->query();
            if ($result->length < 1) return '';
            return $this->formatTxt($result[0]->textContent);
        };

        $this->get['id'] = function () {
            $tagName = '简历编号：';
            $result = $this->xPath->query("//body/p/r/t[starts-with(normalize-space(), '" . $tagName . "')]");
            if ($result->length < 1) return '';
            return $this->preg_get('/(?<=' . $tagName . ')\s*(?<result>.*?)\s*(?=\|)/u', $result[0]->textContent, array('groupName' => 'result'));
        };

        $this->get['time'] = function () {
            $tagName = '最后登录：';
            $result = $this->xPath->query("//body/p/r/t[contains(.,'" . $tagName . "')]");
            if ($result->length < 1) return '';
            return $this->preg_get('/(?<=' . $tagName . ')\s*(?<result>.*?)\s*(?=$)/u', $result[0]->textContent, array('groupName' => 'result'));
        };

        $this->get['name'] = function () {
            $tagName = '姓名：';
            $result = $this->xPath->query("//tbl/tr/tc/p[starts-with(normalize-space(), '" . $tagName . "')]");
            if ($result->length < 1) return '';
            if (count($result) > 1) {
                $result2 = $this->xPath->query("//tbl/tr/tc[normalize-space()='" . $tagName . "']/following-sibling::tc[1]");
                if (count($result2)) return $this->preg_get('/.*?(?=\s*(?:【[^【]+】)?$)/u', $result2[0]->textContent);
            }
            return $this->preg_get('/(?<=' . $tagName . ')\s*(?<result>.*?)\s*(?=$)/u', $result[0]->textContent, array('groupName' => 'result', 'trim' => '*'));
        };

        $this->get['sex'] = function () {
            $tagName = '性别：';
            $result = $this->xPath->query("//tbl/tr/tc/p[starts-with(normalize-space(), '" . $tagName . "')]");
            if ($result->length < 1) return '';
            if (count($result) > 1) {
                $result2 = $this->xPath->query("//tbl/tr/tc[normalize-space()='" . $tagName . "']/following-sibling::tc[1]");
                if (count($result2)) return $this->formatTxt($result2[0]->textContent);
            }
            return $this->preg_get('/(?<=' . $tagName . ').*?(?<result>[男女])性?.*(?=$)/u', $result[0]->textContent, array('groupName' => 'result', 'trim' => '*'));
        };

        $this->get['nation'] = $this->tagNotExist;

        $this->get['identitycard'] = $this->tagNotExist;

        $this->get['mobile'] = function () {
            $result2 = $this->xPath->query("//tbl/tr/tc[normalize-space()='手机号码：']/following-sibling::tc[1]");
            if (count($result2)) return $this->formatTxt($result2[0]->textContent);
            $tagName = '联系电话：';
            $result = $this->xPath->query("//tbl/tr/tc/p[starts-with(normalize-space(), '" . $tagName . "')]");
            if ($result->length < 1) return '';
            return $this->preg_get('/(?<=' . $tagName . ')\s*(?<result>.*?)\s*(?=[\x{4e00}-\x{9fff}]|$)/u', $result[0]->textContent, array('groupName' => 'result', 'trim' => '*'));
        };

        $this->get['email'] = function () {
            $tagName = '电子邮件：';
            $result = $this->xPath->query("//tbl/tr/tc/p[starts-with(normalize-space(), '" . $tagName . "')]");
            if ($result->length < 1) return '';
            if (count($result) > 1) {
                $result2 = $this->xPath->query("//tbl/tr/tc[normalize-space()='" . $tagName . "']/following-sibling::tc[1]");
                if (count($result2)) return $this->preg_get('/\S+@[\w\-]+\.\S+/u', $result2[0]->textContent);
            }
            return $this->preg_get('/(?<=' . $tagName . ')\s*(?<result>\S+@[\w\-]+\.\S+)/u', $result[0]->textContent, array('groupName' => 'result', 'trim' => '*'));
        };

        $this->get['age'] = function () {
            $tagName = '年龄：';
            $result = $this->xPath->query("//tbl/tr/tc/p[starts-with(normalize-space(), '" . $tagName . "')]");
            if ($result->length < 1) return '';
            if (count($result) > 1) {
                $result2 = $this->xPath->query("//tbl/tr/tc[normalize-space()='" . $tagName . "']/following-sibling::tc[1]");
                if (count($result2) && preg_match('/^(?<age>\d+)(?:\s*（(?<birthday>\d+)）)?$/u', $this->formatTxt($result2[0]->textContent), $matches)) {
                    return $matches['age'];
                }
            }
            return $this->preg_get('/(?<=' . $tagName . ')\s*(?<result>.*?)\s*(?=$)/u', $result[0]->textContent, array('groupName' => 'result'));
        };

        $this->get['married'] = $this->tagNotExist;

        $this->get['politic'] = $this->tagNotExist;

        $this->get['degree'] = function () {
            $tagName = '学历：';
            $result = $this->xPath->query("//tbl/tr/tc/p[starts-with(normalize-space(), '" . $tagName . "')]");
            if ($result->length < 1) return '';
            return $this->preg_get('/(?<=' . $tagName . ')\s*(?<result>.*?)\s*(?=$)/u', $result[0]->textContent, array('groupName' => 'result'));
        };

        $this->get['industry'] = function () {
            $tagName = '期望行业：';
            $result = $this->xPath->query("//tbl/tr/tc/p[starts-with(normalize-space(), '" . $tagName . "')]");
            if ($result->length < 1) return '';
            return $this->preg_get('/(?<=' . $tagName . ')\s*(?<result>.*?)\s*(?=$)/u', $result[0]->textContent, array('groupName' => 'result'));
        };

        $this->get['position'] = function () {
            $tagName = '期望职位：';
            $result = $this->xPath->query("//tbl/tr/tc/p[starts-with(normalize-space(), '" . $tagName . "')]");
            if ($result->length < 1) return '';
            return $this->preg_get('/(?<=' . $tagName . ')\s*(?<result>.*?)\s*(?=$)/u', $result[0]->textContent, array('groupName' => 'result'));
        };

        $this->get['career'] = $this->tagNotExist;

        $this->get['major'] = $this->tagNotExist;

        $this->get['birthday'] = function () {
            $result = $this->xPath->query("//tbl/tr/tc[normalize-space()='年龄：']/following-sibling::tc[1][contains(.,'（')]");
            if ($result->length < 1) return '';
            if (preg_match('/^(?<age>\d+)(?:\s*（(?<birthday>[^（]+)）)?$/u', $this->formatTxt($result[0]->textContent), $matches)) {
                if (!empty($matches['birthday'])) return $matches['birthday'];
            }
            return '';
        };

        $this->get['workyear'] = function () {
            $tagName = '工作年限：';
            $result = $this->xPath->query("//tbl/tr/tc/p[starts-with(normalize-space(), '" . $tagName . "')]");
            if ($result->length < 1) return '';
            return $this->preg_get('/(?<=' . $tagName . ')\s*(?<result>.*?)\s*(?=$)/u', $result[0]->textContent, array('groupName' => 'result'));
        };

        $this->get['workarea'] = function () {
            $tagName = '所在地：';
            $result = $this->xPath->query("//tbl/tr/tc/p[starts-with(normalize-space(), '" . $tagName . "')]");
            if ($result->length < 1) return '';
            return $this->preg_get('/(?<=' . $tagName . ')\s*(?<result>.*?)\s*(?=$)/u', $result[0]->textContent, array('groupName' => 'result'));
        };

        $this->get['expectarea'] = function () {
            $tagName = '期望地点：';
            $result = $this->xPath->query("//tbl/tr/tc/p[starts-with(normalize-space(), '" . $tagName . "')]");
            if ($result->length < 1) return '';
            return $this->preg_get('/(?<=' . $tagName . ')\s*(?<result>.*?)\s*(?=$)/u', $result[0]->textContent, array('groupName' => 'result'));
        };

        $this->get['area'] = $this->tagNotExist;

        $this->get['salary'] = function () {
            $tagName = '目前薪资：';
            $result = $this->xPath->query("//tbl/tr/tc/p[starts-with(normalize-space(), '" . $tagName . "')]");
            if ($result->length < 1) return '';
            $resultText = $this->preg_get('/(?<=' . $tagName . ')\s*(?<result>.*?)\s*(?=$)/u', $result[0]->textContent, array('groupName' => 'result'));
            $salary = $this->func->parseSalary($resultText);
            if (count($salary)) {
                $this->helper->resumeInfo['salaryfrom'] = $salary['monthly']['begin'];
                $this->helper->resumeInfo['salaryend'] = $salary['monthly']['end'];
                //$this->helper->resumeInfo['salaryafrom'] = $salary['annual']['begin'];
                //$this->helper->resumeInfo['salaryaend'] = $salary['annual']['end'];
            }
            return $resultText;
        };

        $this->get['expectsalary'] = function () {
            $tagName = '期望月薪：';
            $result = $this->xPath->query("//tbl/tr/tc/p[starts-with(normalize-space(), '" . $tagName . "')]");
            if ($result->length < 1) return '';
            $resultText = $this->preg_get('/(?<=' . $tagName . ')\s*(?<result>.*?)\s*(?=$)/u', $result[0]->textContent, array('groupName' => 'result'));
            $expectsalary = $this->func->parseSalary($resultText);
            if (count($expectsalary)) {
                $this->helper->resumeInfo['expectsalaryfrom'] = $expectsalary['monthly']['begin'];
                $this->helper->resumeInfo['expectsalaryend'] = $expectsalary['monthly']['end'];
                //$this->helper->resumeInfo['expectsalaryafrom'] = $expectsalary['annual']['begin'];
                //$this->helper->resumeInfo['expectsalaryaend'] = $expectsalary['annual']['end'];
            }
            return $resultText;
        };

        $this->get['jobterm'] = $this->tagNotExist;

        $this->get['school'] = $this->tagNotExist;

        $this->get['nofocuse'] = function () {
            $result = $this->xPath->query("//tbl/tr/tc/p[contains(., '勿') and contains(., '推荐企业：')]");
            if ($result->length < 1) return '';
            return $this->preg_get('/(?:勿\s*推荐企业：)\s*(?<result>.*?)\s*(?=$)/u', $result[0]->textContent, array('groupName' => 'result', 'format' => 2));
        };

        $this->get['workinfo'] = function () {
            //$this->listXPath("//body/p[normalize-space()='工作经历' and ppr/pbdr/bottom[@*[local-name()='w:color' and .='E7E7E7']]]/following-sibling::p[ppr/shd[@*[local-name()='w:fill' and .='E6E6E6']]]");
            $result = $this->xPath->query("//body/p[normalize-space()='工作经历' and ppr/pbdr/bottom[@*[local-name()='w:color' and .='E7E7E7']]]/following-sibling::p[ppr/shd[@*[local-name()='w:fill' and .='E6E6E6']]]");
            $data = array();
            foreach ($result as $workInfo) {
                $item = array('comment' => '');
                if (count($this->xPath->query("ppr/rpr/color[@*[local-name()='w:val' and .='333333']]", $workInfo)) && preg_match('/(?<time>\d{4}\.\d{1,2}(?:\.\d{1,2})?\s*-\s*(?:\d{4}\.\d{1,2}(?:\.\d{1,2})?|至今))\s*(?<company>.*?)\s*(?:[(（](?<timespan>(?:\d{1,2}年(?:\s{0,2}[01]?\d个?月)?|\d{1,2}个?月)(?:以上|\+)?)[)）])?$/us', $this->formatTxt($workInfo->textContent), $matches)) {
                    $item['time'] = $matches['time'];
                    $item['company'] = $this->formatTxt($matches['company'], TRUE);
                    $item['comment'] = !empty($matches['timespan']) ? '工作时间：' . $matches['timespan'] : '';
                    $tmp = $this->func->parseTimespan($item['time']);
                    $item['time_from'] = $tmp['begin'];
                    $item['time_end'] = $tmp['end'];
                }
                $companyInfo = $this->xPath->query("following-sibling::tbl[1]", $workInfo);
                $tcArr = $this->xPath->query("tr/tc/p", $companyInfo[0]);
                $hasIndustry = false;
                foreach ($tcArr as $tc) {
                    if (!empty($text = $this->formatTxt($tc->textContent))) {
                        if (!$hasIndustry && count($industryArr = $this->translateHelper->getIndustryCode($text, false, true))) {
                            $item['industry'] = array_key_first($industryArr);
                            $text = str_replace($item['industry'], '', $text);
                            $text = preg_replace('/(?:\s*\|\s*){2,}/u', ' | ', $text);
                            $text = trim($text, " \t\n\r\0\x0B|");
                            $hasIndustry = true;
                            if (!empty($text)) $item['comment'] .= "\r\n" . $text;
                        } elseif ($text != '更多') {
                            $item['comment'] .= "\r\n" . $text;
                        }
                    }
                }
                $table = $this->xPath->query("following-sibling::tbl[2]", $workInfo);
                if (!$table->length) continue;
                $table = $table[0];
                $duty_salary = $this->xPath->query("tr[1]", $table);
                if ($duty_salary->length) {
                    if (preg_match('/^(?<duty>.*?)??\s*(?<salary>\d+(?:\.\d+)?\s*[kw万]?\s*元?(?:\s*[-–—~～至到]\s*\d+(?:\.\d+)?\s*[kw万]?\s*元?)?\s*[\/每][^\r\n]?)?$/us', $this->formatTxt($duty_salary[0]->textContent), $matches)) {
                        $item['duty'] = !empty($matches['duty']) ? $this->formatTxt($matches['duty'], TRUE) : '';
                        $item['salary'] = !empty($matches['salary']) ? $this->formatTxt($matches['salary'], TRUE) : '';
                    }
                }
                $tcArr = $this->xPath->query("tr[1]/following-sibling::tr/tc/p", $table);
                foreach ($tcArr as $tc) {
                    if (!empty($text = $this->recoverText($tc->textContent)))
                        $item['comment'] .= "\r\n" . $text;
                }
                $item['comment'] = trim($item['comment']);
                $data[] = $item;
            }
            return $data;
        };

        $this->get['projectinfo'] = function () {
            $result = $this->getPart('项目经历', true);
            if (!count($result)) return '';
            $data = array();
            foreach ($result as $table) {
                $item = array('comment' => '');

                $project = $this->xPath->query("tr[contains(., '-')][1]", $table);
                if (preg_match('/^\s*(?<time>\d{4}\.\d{1,2}(?:\.\d{1,2})?\s*-\s*(?:\d{4}\.\d{1,2}(?:\.\d{1,2})?|至今))\s*(?<project>.*)\s*$/us', $this->formatTxt($project[0]->textContent), $matches)) {
                    $item['time'] = $matches['time'];
                    $item['project'] = $this->formatTxt($matches['project'], TRUE);
                    $tmp = $this->func->parseTimespan($item['time']);
                    $item['time_from'] = $tmp['begin'];
                    $item['time_end'] = $tmp['end'];
                }
                $duty = $this->xPath->query("tr[starts-with(normalize-space(), '项目职务：')]", $table);
                if ($duty->length) $item['duty'] = $this->preg_get('/(?:项目职务：)\s*(?<result>.*?)\s*(?=$)/u', $duty[0]->textContent, array('groupName' => 'result', 'format' => 2));
                $company = $this->xPath->query("tr[starts-with(normalize-space(), '所在公司：')]", $table);
                if ($company->length) $item['company'] = $this->preg_get('/(?:所在公司：)\s*(?<result>.*?)\s*(?=$)/u', $company[0]->textContent, array('groupName' => 'result', 'format' => 2));

                $other = $this->xPath->query("following-sibling::tr[not(starts-with(normalize-space(), '项目职务：') or starts-with(normalize-space(), '所在公司：'))]/tc/p", $project[0]);

                $trimCount = 0;
                foreach ($other as $node) {
                    $text = $this->formatTxt($node->textContent);
                    if (!$trimCount) $text = preg_replace('/^项目简介\s*：\s*/u', '', $text, -1, $trimCount);
                    $item['comment'] .= "\r\n" . $text;
                }
                $item['comment'] = trim($item['comment']);
                $data[] = $item;
            }
            return $data;
        };

        $this->get['educationinfo'] = function () {
            $result = $this->getPart('教育经历', true, 'p');
            if (!count($result)) return '';

            $data = array();
            $index = 0;
            foreach ($result as $p) {
                if (!isset($item)) {
                    if (preg_match('/^\s*(?<school>.*?)\s*（\s*(?<time>\d{4}\.\d{1,2}(?:\.\d{1,2})?\s*-\s*(?:\d{4}\.\d{1,2}(?:\.\d{1,2})?|至今))\s*）\s*$/us', $this->formatTxt($p->textContent), $matches)) {
                        $index = 0;
                        $item = array(
                            'comment' => '',
                            'time' => $matches['time'],
                            'school' => $this->formatTxt($matches['school'], TRUE),
                        );
                        $tmp = $this->func->parseTimespan($item['time']);
                        $item['time_from'] = $tmp['begin'];
                        $item['time_end'] = $tmp['end'];
                    }
                } else {
                    switch ($index) {
                        case 1:
                            if (preg_match('/^\s*(?<degree>.*?)\s*\|\s*(?<major>.*?)\s*$/us', $this->formatTxt($p->textContent), $matches)) {
                                $item['degree'] = $this->formatTxt($matches['degree'], TRUE);
                                $item['major'] = $this->formatTxt($matches['major'], TRUE);
                            }
                            break;
                        case 2:
                            $item['comment'] .= $this->recoverText($p->textContent);
                            $data[] = $item;
                            unset($item);
                            break;
                    }
                }
                $index++;
            }
            return $data;
        };

        $this->get['skillinfo'] = function () {
            $skillText = '';
            if (!empty($tmp = $this->getPart('我的技能'))) {
                $skillText .= "\r\n" . $tmp;
            }
            if (!empty($tmp = $this->getPart('语言能力'))) {
                $skillText .= "\r\n语言能力：" . $tmp;
            }
            return trim($skillText);
        };

        $this->get['awardinfo'] = $this->tagNotExist;

        $this->get['commentinfo'] = function () {
            return $this->getPart('自我评价');
        };

        $this->get['otherinfo'] = function () {
            $rInfo = &$this->helper->resumeInfo;
            if (empty(trim($rInfo['mobile'])) || empty(trim($rInfo['email'])) || empty(trim($rInfo['workyear'])) || empty(trim($rInfo['name']))) {
                if (count($part = $this->getPart('个人信息', true, 'tbl//drawing'))
                    && count($idNode = $this->xPath->query("descendant::pic[1]/blipfill/blip/@*[local-name()='r:embed']", $part[0]))
                    && !empty($this->helper->resume['resumeImage'][$idNode[0]->textContent])) {
                    $res = $this->func->getInfoFromImg(base64_encode($this->helper->resume['resumeImage'][$idNode[0]->textContent]['data']));
                    if ($res['result'] == 1) {
                        $info = $res['message'];
                        if (isset($info['phone']) && empty(trim($rInfo['mobile']))) $rInfo['mobile'] = $info['phone'];
                        if (isset($info['email']) && empty(trim($rInfo['email']))) $rInfo['email'] = $info['email'];
                        if (isset($info['year']) && empty(trim($rInfo['workyear']))) $rInfo['workyear'] = $info['year'];
                        if (isset($info['name']) && empty(trim($rInfo['name']))) $rInfo['name'] = $info['name'];
                    } else {
                        Log::error('调用OCR服务失败', ['result' => $res], 'cmd');
                    }
                }
            }
            $resultText = '';
            $result = $this->xPath->query("//body/p/r/t[normalize-space()='个人信息']/../../following-sibling::p[1]");
            if ($result->length) $resultText .= "\r\n" . $this->recoverText($result[0]->textContent);
            $part = $this->getPart('附加消息');
            if (!empty($part)) $resultText .= "\r\n" . '附加消息' . "\r\n" . $part;
            return trim($resultText);
        };

        $this->get['avatar'] = function () {
            try {
                if (!count($part = $this->getPart('个人信息', true, 'p//drawing'))) return '';
                if (!count($idNode = $this->xPath->query("descendant::pic[1]/blipfill/blip/@*[local-name()='r:embed']", $part[0]))) return '';
                if (count($sourceNode = $this->xPath->query("descendant::nvpicpr[1]/cnvpr/@descr", $part[0]))
                    && preg_match('/^https:\/\/image0\.lietou-static\.com\/normal\/5ca47b[a-z1-9]{2}509919fa0ea15b[a-z1-9]{2}05u\.png$/i',
                        $url = $sourceNode[0]->textContent)) {
                    return '';  //猎聘有一系列预置头像，没有导入价值
                }

                $imgInfo =& $this->helper->resume['resumeImage'][$idNode[0]->textContent];
                return ['data' => &$imgInfo['data'], 'name' => basename($url ?? $imgInfo['name'])];
            } catch (\Exception $e) {
                Log::error(e_dump($e), ['avatar' => $url ?? ''], 'cmd');
                return '';
            }
        };
    }
}
